package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"store/model/mysql"
	"store/model/redis"
	"store/pkg"

	"store/storerpc/internal/svc"
	"store/storerpc/storerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *storerpc.UpdateRequest) (*storerpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("sendsmslist" + in.Account + in.Source)

	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信验证失败,请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Model(&user).Where("account = ?", in.Account).Find(&user)

	update := mysql.User{
		Model:    gorm.Model{ID: uint(in.Id)},
		Account:  in.Account,
		Password: pkg.MD5(in.Password),
	}
	if user.Password == pkg.MD5(in.NewPassword) {
		return nil, fmt.Errorf("新密码不能等于旧密码")
	}

	if update.ID == 0 {
		return nil, fmt.Errorf("修改账户不存在,请重新输入")
	}

	update.Password = pkg.MD5(in.Password)
	mysql.DB.Debug().Model(&update).Updates(&update)

	return &storerpc.UpdateResponse{Id: int64(update.ID)}, nil
}
